﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;
using System.Configuration;

using System.Text;
using System.Data;

namespace LoginWithFacebook
{
    public partial class LoginWithFacebook : System.Web.UI.Page
    {

        public string FacebookID = "" ;
        public string FirstName = "";
        public string LastName = "";
        public string Email = "";
        public string Facebook_ClientID = "";
        public string Facbook_ReturnURL = "";

        protected void Page_Load(object sender, EventArgs e)
        {

            Facebook_ClientID = ConfigurationSettings.AppSettings["Facebook_ClientID"].ToString();
            Facbook_ReturnURL = ConfigurationSettings.AppSettings["Facbook_ReturnURL"].ToString();


            if (Request.QueryString["access_token"] != null)
            {
        
                String URI = "https://graph.facebook.com/me?access_token=" + Request.QueryString["access_token"].ToString();

                WebClient webClient = new WebClient();
                Stream stream = webClient.OpenRead(URI);
                string b;
                using (StreamReader br = new StreamReader(stream))
                {
                    b = br.ReadToEnd();
                }

               
                Array ar = b.Split(",".ToCharArray());
                for (int p = 0; p < ar.Length; p++)
                {
                    ar.SetValue(ar.GetValue(p).ToString().Trim().Replace("\"", "").Replace("{", "").Replace(":"," "), p);
                }
                for (int p = 0; p < ar.Length; p++)
                {
                    string g = ar.GetValue(p).ToString();
                    if (g.IndexOf("id") >= 0)
                    {
                        
                        g = g.Replace("id", "");
                        if (FacebookID.Length == 0)
                            FacebookID = g;
                    }
                    else if (g.IndexOf("first_name") >= 0)
                    {

                        g = g.Replace("first_name", "");
                        if (FirstName.Length== 0)
                        FirstName = g;
                    }
                    else if (g.IndexOf("last_name") >= 0)
                    {
                        g = g.Replace("last_name", "");
                        if (LastName.Length  == 0)
                        LastName = g;
                    }
                    else if (g.IndexOf("email") >= 0)
                    {
                        g = g.Replace("email", "");
                        if (Email.Length == 0)
                            Email = g.Replace("\\u0040","@");
                    }
                }


        

            }
        }
    }
}